
import 'dart:io';

import 'package:baselib/utils/file_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:framelib/config/app_config.dart';
import 'package:framelib/net/base_entity.dart';
import 'package:module_business/comm/model/FileEntity.dart';
import 'package:module_business/comm/service/comm_service.dart';
import 'package:dio/dio.dart';

/**
 * 结合minio或者AWS S3兼容使用
 * 1、先获取临时上传文件链接和filekey，采用数据流put方法，将文件通过上传链接上传到指定位置，
 * 例如获取上传链接：http://172.16.0.147:9000/testfile/2024/12/20/fe1b5dbc08314d6bb41d286715fadaf0.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241220T061328Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3599&X-Amz-Credential=qATtDR1CdG9pAqlHmWgG%2F20241220%2F%2Fs3%2Faws4_request&X-Amz-Signature=b96cd03c56a0c3c828c9d2d48af8f44f582bf489e9854cf5b9c5c6894c85d219
 * 2、查看上传的文件时：通过filekey获取已上传的文件
 */
class OssFileKeyUtil{
  static final OssFileKeyUtil _singleton = OssFileKeyUtil._internal();

  static OssFileKeyUtil get instance => OssFileKeyUtil();

  factory OssFileKeyUtil() {
    return _singleton;
  }

  OssFileKeyUtil._internal(){
    //做一些操作
  }

  // 上传多个文件
  Future<List<FileEntity>> upLoadFiles(List<File> files) async {
    List<FileEntity> scenePhotos = [];
    for (int i = 0; i < files.length; i++) {
      final baseEntity = await uploadToOss(filePath: files[i]?.path??'');
      if(baseEntity?.code==AppConfig.instance.SUCCESS_CODE){
        // Map<String,dynamic> uploadResultMap = baseEntity?.data??{};
        FileEntity? uploadResult = baseEntity?.data;
        //'fileKey':fileKey,
        //'fileUrl':fileResultUrl,
        //'fileName':fileName,
        if(uploadResult!=null){
          scenePhotos.add(uploadResult);
        }
      }
    }
    return scenePhotos;
  }

  //
  Future<BaseEntity<FileEntity>> uploadToOss({required String filePath})async{
    File fileTemp = File(filePath);
    LogUtil.d('fileTemp.readAsBytesSync()=${fileTemp.readAsBytesSync().length}');
    if(fileTemp.readAsBytesSync().length>(5*1024*1024*1024)){
      // ToastUtil.toast('请上传小于5M的文件');
      return BaseEntity(code: 201, msg: '请上传小于5G的文件');
    }
    String fileName = FileUtil.getFileName(filePath: filePath);
    BaseEntity uploadUrlBaseEntity = await getUploadUrl(fileName: fileName);
    if(uploadUrlBaseEntity?.code == AppConfig.instance.SUCCESS_CODE){
      // Map<String,dynamic> uploadUrlMap = await getUploadUrl(fileName: fileName)??{};
      LogUtil.d('getUploadUrl-->uploadUrlMap=${uploadUrlBaseEntity?.data}');
      Map<String,dynamic> uploadDataMap = uploadUrlBaseEntity?.data??{};
      if(uploadDataMap.isNotEmpty){
        String fileKey = uploadDataMap['fileKey'];
        String fileUrl = uploadDataMap['url'];
        BaseEntity uploadBaseEntity = await uploadFile(uploadUrl: fileUrl, fileName: fileName, file: fileTemp);
        if(uploadBaseEntity.code == AppConfig.instance.SUCCESS_CODE){
          BaseEntity? baseEntity = await getFileAddress(fileKey: fileKey);
          if(baseEntity?.code == AppConfig.instance.SUCCESS_CODE){
            LogUtil.d('getUploadUrl-->baseEntity=${baseEntity?.toJson()}');
            String fileResultUrl = (baseEntity?.data??'');
            LogUtil.d('getFileAddress-->fileResultUrl=$fileResultUrl');
            return BaseEntity(code: 200, msg: '上传成功', data: FileEntity.fromJson({
              'fileKey':fileKey,
              'fileUrl':fileResultUrl,
              'fileName':fileName,
            }));
          }else{
            return BaseEntity(code: baseEntity?.code, msg: baseEntity?.msg);
          }
        }else{
          return BaseEntity(code: uploadBaseEntity?.code, msg: uploadBaseEntity?.msg);
        }
      }else{
        return BaseEntity(code: uploadUrlBaseEntity?.code, msg: uploadUrlBaseEntity?.msg);
      }
    }else{
      return BaseEntity(code: uploadUrlBaseEntity?.code, msg: uploadUrlBaseEntity?.msg);
    }
  }

  //获取上传链接
  Future<BaseEntity> getUploadUrl({required String fileName})async{
    CommService commService = CommService();
    Map<String, dynamic>? parmsMap={
      'fileName' : fileName
    };
    BaseEntity baseEntity = await commService.getUploadUrl(parmsMap: parmsMap);
    return baseEntity;
  }
  //获取文件临时展示链接
  Future<BaseEntity?> getFileAddress({required String fileKey})async{
    CommService commService = CommService();
    BaseEntity baseEntity = await commService.getTempFileByFileKey(fileKey: fileKey);
    return baseEntity;
  }

  //开始上传
  Future<BaseEntity> uploadFile({required String uploadUrl,required String fileName,required File file})async{
    CommService commService = CommService();
    BaseEntity baseEntity = await commService.uploadFile(uploadUrl: uploadUrl,fileName: fileName,file: file);
    return baseEntity;
  }



}